package com.example.service.Impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mapper.UserDepartmentMapper;
import com.example.pojo.entity.UserDepartment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * TODO
 *
 * @author ding
 * @since 2024/6/13
 */
@Service
@DS("master")
public class UserDepartmentServiceImpl extends ServiceImpl<UserDepartmentMapper, UserDepartment>{

    @Autowired
    private UserDepartmentMapper departmentMapper;

    public void add(UserDepartment userDepartment){
        userDepartment.setIsDeleted(0);
        departmentMapper.insert(userDepartment);
    }

    public void update(UserDepartment userDepartment){
        departmentMapper.updateById(userDepartment);
    }

    /**departmentMapper.updateById(userDepartment);
     * 根据id删除数据
     */
    public void delete(int id){
        UserDepartment userDepartment = departmentMapper.selectById(id);
        userDepartment.setIsDeleted(1);
        update(userDepartment);
    }

    /**
     * 根据部门id统计该部门的所有员工数量
     */
    public int countById(int departmentId){
        QueryWrapper<UserDepartment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("department_id",departmentId);
        long count = count(queryWrapper);
        return Math.toIntExact(count);
    }

    /**
     * 删除部门后删除该部门所有员工信息
     */
    public void deleteByDepartmentId(Integer departmentId){
        QueryWrapper<UserDepartment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("department_id",departmentId);
        List<UserDepartment> list = list(queryWrapper);
        for (UserDepartment userDepartment : list) {
            delete(userDepartment.getId());
        }
    }

}
